<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\User;
use Illuminate\Support\Facades\Cache;
use App\Services\TransferGoldBean\TransferGoldBean;
use App\Http\Controllers\Api\V1\Queries\GoldBeanQuery;
use App\Services\TransferGoldBean\TransferGoldBeanRequest;

class GoldBeansController extends Controller
{
	public function index(GoldBeanQuery $query): array
	{
		$user = request()->user();
		$condition = request('condition');
		$query = $query->where('user_id', $user->id);
		$query = !empty(request('start_time')) ? $query->where('created_at', '>', request('start_time')) : $query;
		$query = !empty(request('end_time')) ? $query->where('created_at', '<', request('end_time')) : $query;
		
		$total = $query->inquire($condition)->sum('money');
		$beans = $query->inquire($condition)->orderByDesc('id')->paginate();

		foreach($beans as $k=>$v){
			$jsonData = !empty($v['data']) ? $v['data'] : [];
			if($v['remark'] == "transfered_out_beans" && isset($jsonData['child_user_id'])) {

				$beans[$k]['name'] =  !empty(User::find($jsonData['child_user_id'])) ? User::find($jsonData['child_user_id'])->name : '';
			}elseif($v['remark'] == "transfered_in_beans"  && isset($jsonData['parent_user_id'])) {
				$beans[$k]['name'] = !empty(User::find($jsonData['parent_user_id'])) ? User::find($jsonData['parent_user_id'])->name : '';
			}else{
				$beans[$k]['name'] = "";
			}

		}
		return ['total' => $total, 'data' => $beans];
	}

	public function transfer()
	{
		$lock = Cache::lock('beans_transfer', 1);

		try {

			if (! $lock->get()) fail('处理中...请勿频繁操作');

			$request = app(TransferGoldBeanRequest::class);

			$user = $request->user();

			app(TransferGoldBean::class, [
				'self' => $user,
				'child' => $request->getChild(),
				'beans' => $request->amount,
			])->apply();


		} finally {
			$lock->release();
		}

		return response(null, 204);
	}


	public function config()
	{
		$data = [6,30,98,168,328,648];
		
		return $data;
	}
}
